<template>
  <div class="app-container">

    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="岗位编码" prop="code">
        <el-input v-model="queryParams.code" placeholder="请输入岗位编码" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="岗位名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入岗位名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <!--      <el-form-item label="节点类型（目录、岗位）" prop="kindId">
              <el-input v-model="queryParams.kindId" placeholder="请输入节点类型（目录、岗位）" clearable @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="父ID" prop="parentId">
              <el-input v-model="queryParams.parentId" placeholder="请输入父ID" clearable @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="业务类别编码" prop="businessCode">
              <el-input v-model="queryParams.businessCode" placeholder="请输入业务类别编码" clearable @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="queryParams.remark" placeholder="请输入备注" clearable @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="序号" prop="sort">
              <el-input v-model="queryParams.sort" placeholder="请输入序号" clearable @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="落位人员" prop="dataValues">
              <el-input v-model="queryParams.dataValues" placeholder="请输入落位人员" clearable @keyup.enter.native="handleQuery"/>
            </el-form-item>-->
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态 0有效，1无效" clearable size="small">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.COMMON_STATUS)"
                     :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
      <el-form-item label=" " prop="showDisabled">
        <el-checkbox @change="checkShowFullName">显示全路径</el-checkbox>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['sa:business-manager-matrix:create']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   :loading="exportLoading"
                   v-hasPermi="['sa:business-manager-matrix:export']">导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading"
              border
              @cell-click="handleEditPerson"
              :data="list">
      <el-table-column label="序号" align="center" prop="sort" width="60"/>
      <el-table-column label="编码" align="center" prop="code" width="60"/>
      <el-table-column label="名称" align="center" prop="name"/>
      <!--      <el-table-column label="类型" align="center" prop="kindId" />-->
      <!--      <el-table-column label="业务类别" align="center" prop="businessCode" />-->
<!--      <el-table-column label="备注" align="center" prop="remark"/>-->
      <el-table-column v-if="refreshColumn" label="人员" align="center" prop="dataValues">
        <template slot-scope="scope">
          <el-tooltip v-if="!showFullName" placement="top">
            <div slot="content">
              {{ filterManagerConfigText(scope.row, 'orgFullName') }}
            </div>
            <span>
              {{ filterManagerConfigText(scope.row) }}
            </span>
          </el-tooltip>
          <span v-else>{{ filterManagerConfigText(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template v-slot="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="creator" width="100"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="150">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新人" align="center" prop="updater" width="100"/>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="150">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100">
        <template v-slot="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['sa:business-manager-matrix:update']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['sa:business-manager-matrix:delete']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="500px" v-dialogDrag append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="岗位编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入岗位编码"/>
        </el-form-item>
        <el-form-item label="岗位名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入岗位名称"/>
        </el-form-item>
        <el-form-item label="类型" prop="kindId">
          <el-input v-model="form.kindId" placeholder="请输入节点类型（目录、岗位）"/>
        </el-form-item>
        <el-form-item label="业务类别" prop="businessCode">
          <el-input v-model="form.businessCode" placeholder="业务类别"/>
        </el-form-item>
        <el-form-item label="排序号" prop="sort">
          <el-input-number v-model="form.sort" controls-position="right" :min="0"/>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in this.getDictDatas(DICT_TYPE.COMMON_STATUS)"
                      :key="dict.value" :label="parseInt(dict.value)">{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog title="人员设置" :visible.sync="openConfigDialog" width="800px" height="300" append-to-body>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleUserPicker">添加</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-tickets" size="mini" @click="handleCopyDataValues">复制
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-document" size="mini" @click="handlePasteDataValues">粘贴
          </el-button>
        </el-col>
      </el-row>

      <el-table v-loading="configPersonListLoading"
                height="200"
                :data="editConfigInfo.dataValues"
      >
        <el-table-column label="姓名" align="center" prop="orgName" show-overflow-tooltip/>
        <el-table-column label="路径" align="left" prop="orgFullName" min-width="200" show-overflow-tooltip/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="100">
          <template v-slot="scope">
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteConfigPerson(scope.row.orgId)"
                       v-hasPermi="['sa:oporg-manager-matrix-config:delete']">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitConfigForm">确 定</el-button>
        <el-button @click="closeConfigDialog">关闭</el-button>
      </div>
    </el-dialog>

    <el-dialog title="人员选择" :visible.sync="openUserPicker" width="1200px" append-to-body style="text-align: center;">
      <SaUserPicker :org-kind-id="saPersonPickerOrgKind" @complete="getUserList" @close="openUserPicker = false"/>
    </el-dialog>

  </div>
</template>

<script>
import {
  createBusinessManagerMatrix,
  updateBusinessManagerMatrix,
  deleteBusinessManagerMatrix,
  getBusinessManagerMatrix,
  getBusinessManagerMatrixPage,
  exportBusinessManagerMatrixExcel
} from "@/api/sa/businessManagerMatrix";
import SaUserPicker from '@/components/SaPersonPicker';
import {COMMON_TREE, CommonStatusEnum, OrgKindEnum, SaDataScopeEnum, SaLikeOrIn} from "@/utils/constants";
import {DICT_TYPE, getDictDatas} from "@/utils/dict";

export default {
  name: "BusinessManagerMatrix",
  components: {SaUserPicker},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 职能管理矩阵 列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        code: null,
        name: null,
        kindId: null,
        parentId: null,
        businessCode: null,
        remark: null,
        sort: null,
        dataValues: null,
        status: null,
        version: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      openUserPicker: false,
      configPersonListLoading: false,
      editConfigInfo: {
        id: null,
        dataValues: null,
      },
      showFullName: false,
      saPersonPickerOrgKind: [OrgKindEnum.Position.code, OrgKindEnum.Psm.code].join(","),
      openConfigDialog: false,
      editTableRows: {},
      refreshColumn: true,
      copyDataValues: []
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      getBusinessManagerMatrixPage(this.queryParams).then(response => {
        this.list = response.data.list;
        this.list.forEach(item => {
          item.dataValues = item.dataValues && JSON.parse(item.dataValues) || []
        })
        this.total = response.data.total;
      }).finally(() => {
        this.loading = false;
      });
    },
    filterManagerConfigText(row, field) {
      let dataValues = row.dataValues || []
      let text = []
      if (dataValues && dataValues.length > 0) {
        dataValues.forEach(item => {
          if (!!field) {
            text.push(item[field])
          } else if (!this.showFullName) {
            text.push(item.orgName)
          } else {
            text.push(item.orgFullName)
          }
        })
        return text.join(";  ")
      }
      return ""
    },
    checkShowFullName(val) {
      this.showFullName = val
      this.refreshColumn = false
      this.$nextTick(() => {
        this.refreshColumn = true
      })
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        code: undefined,
        name: undefined,
        kindId: undefined,
        parentId: undefined,
        businessCode: undefined,
        remark: undefined,
        sort: undefined,
        dataValues: undefined,
        status: undefined,
        version: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加职能管理矩阵 ";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getBusinessManagerMatrix(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改职能管理矩阵 ";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        // 修改的提交
        if (this.form.id != null) {
          updateBusinessManagerMatrix(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createBusinessManagerMatrix(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除职能管理矩阵 编号为"' + id + '"的数据项?').then(function () {
        return deleteBusinessManagerMatrix(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.$modal.confirm('是否确认导出所有职能管理矩阵 数据项?').then(() => {
        this.exportLoading = true;
        return exportBusinessManagerMatrixExcel(params);
      }).then(response => {
        this.$download.excel(response, '职能管理矩阵 .xls');
        this.exportLoading = false;
      }).catch(() => {
      });
    },
    handleUserPicker() {
      this.openUserPicker = true
    },
    handleCopyDataValues() {
      this.copyDataValues = [...this.editConfigInfo.dataValues]
    },
    handlePasteDataValues() {
      this.editConfigInfo.dataValues = [...this.copyDataValues]
    },
    handleEditPerson(row, column, cell) {
      if (column.property == 'dataValues') {
        this.editConfigInfo = Object.assign({}, row)
        this.editTableRows = row
        this.openConfigDialog = true
      }
    },
    submitConfigForm() {
      let cloneConfigForm = {
        id: this.editConfigInfo.id,
        dataValues: this.editConfigInfo.dataValues
      }
      let dataValue = []
      if (cloneConfigForm.dataValues && cloneConfigForm.dataValues.length > 0) {
        cloneConfigForm.dataValues.forEach(item => {
          dataValue.push(item)
        })
      }
      cloneConfigForm.dataValues = dataValue.length > 0 ? JSON.stringify(dataValue) : ''
      if (cloneConfigForm.id != null) {
        updateBusinessManagerMatrix(cloneConfigForm).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.openConfigDialog = false
          this.editTableRows.dataValues = this.editConfigInfo.dataValues
          this.refreshColumn = false
          this.$nextTick(() => {
            this.refreshColumn = true
          })
        });
        return;
      }
    },
    closeConfigDialog() {
      this.openConfigDialog = false
    },
    // 删除配置中的人员
    handleDeleteConfigPerson(id) {
      let newData = []
      this.editConfigInfo.dataValues.forEach(item => {
        if (id != item.orgId) {
          newData.push(item)
        }
      })
      this.editConfigInfo.dataValues = newData
    },
    getUserList(userList) {
      this.editConfigInfo.dataValues = this.editConfigInfo.dataValues || []
      let existsDataValues = {}
      this.editConfigInfo.dataValues.forEach(item => {
        existsDataValues[item.orgId] = item
      })
      userList.forEach(item => {
        let d = {
          orgKindId: item.orgKindId,
          orgId: item.id,
          orgFullId: item.fullId,
          orgName: item.name,
          orgFullName: item.fullName
        }
        !existsDataValues[item.id] && this.editConfigInfo.dataValues.push(d)
      })
    },
  }
};
</script>
